﻿

namespace Mulala.Cavan.Application.MainBoundedContext.NannyModule
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Mulala.Cavan.Domain.MainBoundedContext.NannyModule;
    using Mulala.Cavan.Domain.MainBoundedContext.SearchModule;
    using Mulala.Cavan.Domain.Seedwork;
    using Spring.Context;
    using Spring.Context.Support;

    public class NannyDiaryAppService : BaseAppService<NannyDiary, NannyDiarySearch, INannyDiaryRepository>, INannyDiaryAppService
    {
        private IApplicationContext SpringContext = null;
        private INannyAppService NannyAppService { get; set; }

        public override BoolGenericResult<NannyDiary> Add(NannyDiary newNannyDiary)
        {
            this.SpringContext = ContextRegistry.GetContext();
            this.NannyAppService = this.SpringContext.GetObject("NannyAppService") as INannyAppService;

            BoolGenericResult<NannyDiary> result = new BoolGenericResult<NannyDiary>();
            Nanny nanny = this.NannyAppService.GetById(newNannyDiary.Nanny.ID);
            result = nanny.PublishDiary(newNannyDiary.Title, newNannyDiary.Content);

            if (result.IsSuccess)
            {
                this.Repository.Save(result.Object);
            }

            return result;
        }

        public override BoolGenericResult<NannyDiary> Update(NannyDiary changedNannyDiary)
        {
            BoolGenericResult<NannyDiary> result = new BoolGenericResult<NannyDiary>();
            NannyDiary currentNannyDiary = this.Repository.Get(changedNannyDiary.ID);
            Nanny nanny = this.NannyAppService.GetById(changedNannyDiary.Nanny.ID);
            result = nanny.ModifyDiary(currentNannyDiary, changedNannyDiary.Title, changedNannyDiary.Content);

            if (result.IsSuccess)
            {
                this.Repository.Update(currentNannyDiary);
            }

            return result;
        }

        public new BoolGenericResult<NannyDiary> Delete(NannyDiary deletedNannyDiary)
        {
            BoolGenericResult<NannyDiary> result = new BoolGenericResult<NannyDiary>();
            NannyDiary currentNannyDiary = this.Repository.Get(deletedNannyDiary.ID);
            Nanny nanny = this.NannyAppService.GetById(deletedNannyDiary.Nanny.ID);
            result = nanny.DeleteDiary(currentNannyDiary);

            if (result.IsSuccess)
            {
                this.Repository.Update(currentNannyDiary);
            }

            return result;
        }
    }
}
